import Footer from '@/components/Footer';
import { Question, SelectLang } from '@/components/RightContent';
import { ArrowLeftOutlined, LinkOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { Settings as LayoutSettings, MenuDataItem, ProBreadcrumb } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import React, { useRef, useState } from 'react';
import { AvatarDropdown, AvatarName } from './components/RightContent/AvatarDropdown';
import { Button, message, notification } from 'antd';
import { Route } from 'antd/es/breadcrumb/Breadcrumb';
import baseUrl from './utils/baseUrl';
import { promisemenulist } from './services/user';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  getRoutesList?: () => Promise<string[] | undefined>;
  hasRoutes?: string[]
}> {
  const fetchUserInfo = async () => {
    if(!localStorage.accessToken){
      history.push(loginPath);
    }
    try {
      return {
        name: localStorage.userName,
        avatar: '',
        userid: '',
        address: '',
        phone: ''
      }
    } catch (error) {
      console.log('fetchUserInfo');
      
      history.push(loginPath);
    }
    return undefined;
  };
  const getRoutesList = async () => {
    try {
      let hasRoutes: string[] = []
      const {list} = await promisemenulist({})
      function updateTreeData(list: any[]): any[] {
        const treeList: any[] = list.map((node) => {
          const list = updateTreeData(node.navs)
          hasRoutes = [...new Set(hasRoutes.concat(list, [node.value]))]
          return node.value
        })
        return treeList
      }
      updateTreeData(list[0].navs)

      console.log(hasRoutes);
      return hasRoutes
    } catch (error) {
      console.log('getRoutesList', error);
      history.push(loginPath);
    }
    return undefined;
  }
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    const hasRoutes = await getRoutesList()
    return {
      fetchUserInfo,
      getRoutesList,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
      hasRoutes
    };
  }
  return {
    fetchUserInfo,
    getRoutesList,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}
/**
 * 异常处理程序
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    405: '请求方法不被允许。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
 * @see https://beta-pro.ant.design/docs/request-cn
 */
// 响应拦截
async function responseInterceptors(response: Response) {
  let res = undefined
  try {
    res = await response?.clone()?.json?.();
  } catch (error) {
    res = response
  }
  const { code, msg } = res.data;
  if (code === 0) {
    return { ...res.data, success: true, msg }
  }
  if (code === 201 || code === 700) {
    localStorage.clear()
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login') {
      history.replace({
        pathname: '/user/login'
      });
    }
    // return { errorCode: code, success: false, errorMessage: msg, msg}
  }
  
  throw  {name: 'BizError', showType: 2, info:{
    errorCode: code, errorMessage: msg
  },success: false };
  // return { errorCode: code, success: false, errorMessage: msg, msg }
}
// 请求拦截
function requestInterceptors(url: string, options: any) {
  // 设置代理前缀/api
  const newUrl = baseUrl + url
  return {
    url: newUrl,
    options: {
      ...options,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        accessToken: localStorage.accessToken || ''
      },
    }
  };
}
const MenuItem = ({ path, pro_layout_parentKeys, name, img, collapsed, onClick, hashId }: MenuDataItem) => {
  return <div
    style={{
      display: 'flex',
      alignItems: 'center',
      gap: 8,
      height: '100%',
      justifyContent: collapsed ? 'center' : 'start'
    }}
    className={`ant-pro-base-menu-item-title ${hashId} ${collapsed ? 'ant-pro-base-menu-item-title-collapsed' : ''}`}
    onClick={() => {
      onClick?.()
    }}
  >
    {pro_layout_parentKeys.length == 0 && <img
      style={{ width: '20px', height: '20px' }}
      src={`/menu-icon/${img + (location.pathname.includes(path || '') ? '-active' : '')}.png`}
    />}
    <span className={`ant-pro-base-menu-item-text ${hashId} ant-pro-base-menu-item-text-has-icon`}>
      {name}
    </span>
  </div>
}
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const [collapsed, setCollapsed] = useState(false);
  const pageTitle = useRef<undefined | string>('')
  const routerArray = useRef<undefined | Route[]>([])

  return {
    actionsRender: () => [<SelectLang key="SelectLang" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      console.log('initialState?.currentUser---',initialState?.currentUser);
      
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.replace(loginPath);
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: [],
    collapsed,
    header: true,

    headerContentRender: () => {
      return (
        <span
          onClick={() => setCollapsed(!collapsed)}
          style={{
            cursor: 'pointer',
            fontSize: '16px',
          }}
        >
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </span>
      );
    },
    headerTitleRender: false,

    menuItemRender: (item, _, props) => {
      const { hashId, name } = props as any
      if (item.replace) {
        pageTitle.current = (item.name)
      }

      return <MenuItem
        {...item}
        collapsed={collapsed}
        hashId={hashId}
        onClick={() => {
          history.push(item.path || '')
        }}
      />
    },
    subMenuItemRender: (item, _, props) => {
      const { hashId } = props as any
      return <MenuItem
        {...item}
        collapsed={collapsed}
        hashId={hashId}
      />
    },
    breadcrumbRender: (router) => {
      routerArray.current = router
      return router
    },
    headerRender: (props, defaultDom) => {
      return <div
        style={{ position: 'sticky' }}>
        <div style={{
          background: '#FFFFFF',
          boxShadow: '3px 2px 10px 0px rgba(0,0,0,0.09)',
          padding: '0 8px',
        }}
        >
          {defaultDom}
        </div>
        <div
          style={{
            height: '48px',
            background: '#F7F7F7',
            padding: '0 24px',
            display: 'flex',
            lineHeight: 1,
            alignItems: 'center',
            gap: '10px'
          }}
        >
          {window.history.state.idx > 0 &&
            <Button
              type="primary"
              style={{
                width: '24px',
                height: '24px',
                backgroundColor: '#4370FA',
                borderRadius: '4px',
                color: '#fff',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                padding: 0
              }}
              onClick={() => {
                history.back()
              }}
            >
              <ArrowLeftOutlined />
            </Button>
          }
          <div
            style={{
              fontSize: '16px',
              fontWeight: 500,
              color: '#1B222D'
            }}
          >
            {pageTitle.current}
          </div>
          {(routerArray.current?.length || 0) > 1 && <div
            style={{
              fontSize: '14px',
              color: '#999999',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <div>您所在的位置：</div>
            {routerArray.current?.map(item => <Link
              className={`ant-breadcrumb-link ${item.path == history.location.pathname ? 'active' : ''}`}
              key={item.path}
              to={item.path}
            >
              {item.breadcrumbName}
              <span className='ant-breadcrumb-separator'>/</span>
            </Link>)}
          </div>}
        </div>
      </div>
    },
    menuHeaderRender: () => (
      <div
        style={{
          display: 'flex',
          width: '100%',
          flexDirection: 'column',
          alignItems: 'center',
          gap: 15
        }}
      >
        <div style={{
          height: collapsed ? '34px' : '52px',
          width: collapsed ? '34px' : '52px',
          marginTop: collapsed ? '6px' : '12px',
          marginBottom: collapsed ? '10px' : '0',
        }}>
          <img style={{ width: '100%', height: '100%' }} src='/logo.png' />
        </div>
        {
          !collapsed && <>
            <div style={{ color: '#fff', fontSize: '18px', fontWeight: 'bold', whiteSpace: 'nowrap' }}>
              管理后台
            </div>
            <div style={{ width: 'calc(100% - 10px)', paddingLeft: '6px', paddingTop: '5px', marginBottom: '-10px' }}>
              <div style={{
                fontSize: '14px',
                fontWeight: 400,
                color: '#FFFFFF60',
                textAlign: 'left'
              }}>菜单</div>
            </div>
          </>
        }
      </div>
    ),
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {/* <SettingDrawer
            disableUrlParams
            enableDarkTheme
            settings={initialState?.settings}
            onSettingChange={(settings) => {
              setInitialState((preInitialState) => ({
                ...preInitialState,
                settings,
              }));
            }}
          /> */}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
  requestInterceptors: [requestInterceptors],
  responseInterceptors: [responseInterceptors],
};
